package com.addplus.townmall.server.scheduled.scheduletask;

import com.addplus.townmall.server.api.constant.StringConstant;
import com.addplus.townmall.server.api.mapper.town.PlatformCategoryMapper;
import com.addplus.townmall.server.api.model.town.PlatformCategory;
import com.addplus.townmall.server.connector.redis.RedisSlaveTemplateManager;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;

/**
 * 类名: PlatformCategoryTask
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/12/10 4:03 PM
 * @description 类描述: 平台类目每小时更新类
 */
@Component
public class PlatformCategoryTask {

    private Logger logger = LoggerFactory.getLogger(PlatformCategoryTask.class);

    @Autowired
    private PlatformCategoryMapper platformCategoryMapper;

    @Autowired
    private RedisSlaveTemplateManager templateManager;


    @Scheduled(cron = "0 * * * * *")
    private void processPlatformCategory() throws Exception {
        // 获取一级类目
        QueryWrapper<PlatformCategory> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dept", 1);
        queryWrapper.eq("parent_id", 0);
        queryWrapper.eq("is_deleted", 0);
        queryWrapper.eq("is_online", 1);
        queryWrapper.orderByAsc("sort");
        queryWrapper.select("id");
        List<PlatformCategory> platformCategoryList = platformCategoryMapper.selectList(queryWrapper);
        if (platformCategoryList == null || platformCategoryList.isEmpty()) {
            logger.info("平台类目每小时更新查询一级类目未空");
            return;
        }
        HashMap<Integer, List<Integer>> hashMap = new HashMap<>();
        platformCategoryList.stream().forEach(platformCategory -> {
            List<Integer> platList = platformCategoryMapper.getPlatformCategoryByList(platformCategory.getId());
            if (platList != null && !platList.isEmpty()) {
                hashMap.put(platformCategory.getId(), platList);
            }
        });
        if (hashMap != null && !hashMap.isEmpty()) {
            templateManager.getMasterTemplate().delete(StringConstant.PLATFORM_CATEGORY_BATCH);
            templateManager.getMasterTemplate().opsForHash().putAll(StringConstant.PLATFORM_CATEGORY_BATCH, hashMap);
        }
    }


}
